package com.example.juc.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class B {

    public static void main(String[] args) {
        Data2 data2 = new Data2();

        new Thread(()-> {
            for (int i =0 ;i<10;i++){
                try {
                    data2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()-> {
            try {
                for (int i =0;i<10;i++){
                    data2.decrement();
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B").start();
    }
}


class Data2{

    private int num =0;

    Lock lock = new ReentrantLock();

    Condition condition = lock.newCondition();

    public  void increment() throws InterruptedException {
        lock.lock();
        try {
            if(num!=0){
                condition.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"->"+num);
        }catch (Exception e){

        }finally {
            condition.signalAll();
        }

    }

    public void decrement() throws InterruptedException {
       lock.lock();
       try {
           if (num==0){
               condition.await();
           }
           num--;
           System.out.println(Thread.currentThread().getName()+"->"+num);
       }catch (Exception e){

       }finally {
           condition.signalAll();
       }

    }
}